在很多情況,例如要寫遊戲或是寫一個介面,都需要用到按鍵,當然你可以使用現成的用戶介面library,或者如果你用的是正統python的話,也有很多相關的GUI library可以使用,但自行編寫自己的class的話,除了可以客製化自己的介面和特色外,也可以學習到很多實用內容。

buttonDemo.pyde
xxxxxxxxxx291from button import *2
3buttonWidth = 804buttonHeight = 505
6b1=07b2=08b3=09
10def setup():11 global b1, b2, b312 size(600, 200)13 b1 = Button(width/2-width/4, height/2, buttonWidth, buttonHeight, "Button1")14 b2 = Button(width/2, height/2, buttonWidth, buttonHeight, "Button2")15 b3 = Button(width/2+width/4, height/2, buttonWidth, buttonHeight, "Button3")16
17def draw():18 background(200)19 b1.show()20 b2.show()21 b3.show()22
23def mousePressed():24 if b1.overButton():25 print("button1 pressed")26 if b2.overButton():27 print("button2 pressed")28 if b3.overButton():29 print("button3 pressed")button.py
xxxxxxxxxx271class Button:2 def __init__(self, _bx, _by, _w, _h, _label):3 self.bx = _bx4 self.by = _by5 self.w = _w6 self.h = _h7 self.label = _label8 rectMode(CENTER)9 textAlign(CENTER, CENTER)10 textSize(16)11
12 def show(self):13 stroke('#6F8FFF')14 strokeWeight(4)15 if self.overButton():16 fill('#AAAA00')17 else:18 fill('#FFFF00')19 rect(self.bx, self.by, self.w, self.h,10,10,10,10)20 fill('#000000')21 text(self.label, self.bx, self.by)22
23 def overButton(self):24 if mouseX > self.bx-self.w/2 and mouseX < self.bx + self.w/2 and mouseY > self.by-self.h/2 and mouseY < self.by + self.h/2:25 return True26 else:27 return False